<template>
  <div class="page none-sizing">

    <el-alert :title="title" type="success" />
    <div class="jp-table">
      <vxe-toolbar ref="contractToolbar" :refresh="{query: refreshList}" import export print custom>
        <template #buttons>
          <!-- <el-button @click="showSyncDialog">同步合同</el-button> -->
          <el-button  type="warning" @click="showSyncDialog">同步</el-button>
          <el-button  type="primary" icon="plus" @click="add()" v-if="hasPermission('contract:tPurchaseContract:add')">新增合同</el-button>
          <!-- <el-button v-if="hasPermission('contract:contract:edit')" type="warning" icon="edit-filled" @click="edit()"
            v-show="$refs.contractTable && $refs.contractTable.getCheckboxRecords().length === 1" plain>修改</el-button>
          <el-button v-if="hasPermission('contract:contract:del')" type="danger" icon="del-filled" @click="del()"
            v-show="$refs.contractTable && $refs.contractTable.getCheckboxRecords().length > 0" plain>删除</el-button>-->
        </template>
        <template #tools>
          <vxe-button type="text" :title="
		    searchVisible ? '收起检索' : '展开检索'
		  " icon="vxe-icon-search" class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
          <vxe-button type="text" title="下载导入模板" v-if="hasPermission('contract:contract:import')" icon="vxe-button--icon vxe-icon-file-excel"
            class="tool-btn m-l-0" @click="downloadTpl()">
          </vxe-button>
        </template>
      </vxe-toolbar>
      <div class="jp-table-body">
        <vxe-table border auto-resize resizable height="600" :loading="loading" size="small" ref="contractTable" show-header-overflow 
          highlight-hover-row :menu-config="{}" :print-config="{}" :import-config="{
    importMethod: importMethod,
    types: ['csv', 'xls', 'xlsx'],
    remote: true,
  }" :export-config="{
    remote: true,
    filename: `合同管理数据${moment(new Date()).format(
		'YYYY-MM-DD'
    )}`,
    sheetName: '合同管理数据',
    exportMethod: exportMethod,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all'],
  }" @sort-change="sortChangeHandle" :sort-config="{remote:true}" :data="dataList" :checkbox-config="{}">
          <vxe-column type="seq" width="40"></vxe-column>
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column field="contractCategory"  title="合同类别" width="100px">
            <template #default="{ row }">
              {{ $dictUtils.getDictLabel("contract_type", row.contractCategory, '-') }}
            </template>
          </vxe-column>
          <vxe-column field="contractName"  title="合同名称" width="140px">
          </vxe-column>
          <vxe-column field="contractNo" sortable title="合同编号" width="140px">
          </vxe-column>
          <vxe-column field="downType"  title="类型 " width="100px">
            <template #default="{ row }">
              {{ $dictUtils.getDictLabel("claim_type", row.downType, '-') }}
            </template>
          </vxe-column>
          <vxe-column field="contractAmount" sortable title="合同金额(元)" width="140px">
          </vxe-column>
          <vxe-column field="correctContractAmount" sortable title="修正后合同金额(元)" width="240px">
          </vxe-column>
          <vxe-column field="qualityGuaranteeFund" sortable title="质保金" width="140px">
          </vxe-column>
          <vxe-column field="contractSignTime" sortable title="合同签订时间" width="140px">
          </vxe-column>
          <vxe-column field="supplier.companyName" sortable title="供应商" width="140px">
          </vxe-column>
          <vxe-column field="isScientificResearch"  title="是否科研" width="140px">
            <template #default="{ row }">
              {{ $dictUtils.getDictLabel("yes_no", row.isScientificResearch, '-') }}
            </template>
          </vxe-column>
          <vxe-column field="attachment"  title="附件" width="140px">
            <template #default="{ row }">
              <div @click="previewFiles(row.attachment)" class="file">{{getFileName(row.attachment)}}</div>
            </template>
          </vxe-column>
          <vxe-column field="remark" sortable title="备注" width="140px">
          </vxe-column>

          <vxe-column fixed="right" align="center" width="340" title="操作">
            <template #default="{ row }">

              <el-button  type="primary" text icon="view-filled" @click="view(row.id)">查看</el-button>
              <el-button v-if="row.contractNo&&row.isScientificResearch!=1" type="primary" text icon="plus"
                @click="openResearchDialog(row)">添加科研</el-button>
              <!-- <el-button v-if="hasPermission('contract:contract:view')&&!row.contractNo" type="primary" text icon="plus" @click="add(row.id)">新增</el-button> -->
              <el-button  type="primary" text icon="edit-filled" @click="edit(row.id)">修改</el-button>

              <el-button  type="danger" text icon="del-filled" @click="bindUnbindContract(row.contractNo)">解除合同</el-button>
              <!-- <el-popconfirm title="确认解除合同绑定吗?" @confirm="bindUnbindContract(row.contractNo)" width="260px">
                <template #reference>
                  <el-button type="warning" text>解除合同</el-button>
                </template>
              </el-popconfirm> -->
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize" :total="tablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <ContractForm ref="contractForm" @refreshDataList="refreshList"></ContractForm>

    <!-- 同步合同弹窗 -->
    <el-dialog title="请选择合同" v-model="syncDialogVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="sync-dialog-content">
        <div class="input-label">选择合同</div>
        <!-- <el-input v-model="contractNo" placeholder="请输入合同编号" class="contract-input"></el-input> -->
        <el-select v-model="contractNo" placeholder="请选择" style="width: 80%;">
          <el-option v-for="item in contractList" :key="item.contractNo" :label="item.contractName" :value="item.contractNo">
          </el-option>
        </el-select>
      </div>
      <div class="sync-dialog-content">
        <div class="input-label">合同类别</div>
        <el-select v-model="contractCategory" placeholder="请选择" style="width: 80%;">
          <el-option v-for="item in $dictUtils.getDictList('contract_type')" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="sync-dialog-content">
        <div class="input-label">类&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型</div>
        <el-select v-model="downType" placeholder="请选择" style="width: 80%;">
          <el-option v-for="item in $dictUtils.getDictList('claim_type')" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
   
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmSync">确认并同步</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加科研弹窗 -->
    <el-dialog v-model="researchDialogVisible" title="添加科研" width="1200px" :destroy-on-close="true">
      <el-form ref="researchFormRef" :model="researchForm" label-width="160px" :rules="researchRules">
        <!-- 合同信息部分 -->
        <div class="section-title">合同信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="researchForm.contractName" placeholder="请输入合同名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="researchForm.contractNo" placeholder="请输入合同编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同签订时间" prop="contractSignTime">
              <el-date-picker v-model="researchForm.contractSignTime" type="date" placeholder="选择日期" style="width: 100%" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="合同金额(元)" prop="contractAmount">
              <el-input v-model="researchForm.contractAmount" placeholder="请输入合同金额" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="修正后合同金额(元)" prop="correctContractAmount">
              <el-input v-model="researchForm.correctContractAmount" placeholder="请输入修正后合同金额" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-input v-model="researchForm.taxRate" placeholder="请输入税率" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="合同类别" prop="contractCategory">
              <el-select v-model="researchForm.contractCategory" placeholder="请选择合同类别" style="width: 100%" disabled>
                <el-option v-for="item in $dictUtils.getDictList('contract_type')" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供货商名称" prop="supplierName">
              <el-input v-model="researchForm.supplierName" placeholder="请输入供货商名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 课题信息部分 -->
        <div class="section-title">课题信息</div>
        <el-radio-group v-model="activeTab" style="margin:0 0 20px 20px;">
          <el-radio value="1" border>整个合同金额作为课题</el-radio>
          <el-radio value="2" border>部分合同金额作为课题</el-radio>
        </el-radio-group>
        <template v-if="activeTab==2">
          <el-form-item label="课题名称" prop="topicName">
            <el-input v-model="researchForm.topicName" placeholder="请输入课题名称" />
          </el-form-item>
          <el-form-item label="修正后金额" prop="correctTopicAmount">
            <el-input v-model="researchForm.correctTopicAmount" placeholder="请输入修正后金额" />
          </el-form-item>
          <el-form-item label="税率(%)" prop="topicTaxRate">
            <el-input v-model="researchForm.topicTaxRate" placeholder="请输入税率" />
          </el-form-item>
          <el-form-item label="税额" prop="taxAmount">
            <el-input v-model="researchForm.taxAmount" placeholder="请输入税额" />
          </el-form-item>
        </template>

        <div class="dialog-footer">
          <el-button @click="researchDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResearchForm">确认并保存</el-button>
        </div>
      </el-form>
    </el-dialog>
   <!-- 引入文件预览组件 -->
   <FilePreview ref="filePreview" />
  </div>
</template>

<script>
import ContractForm from './ContractForm'
import predictContractService from '@/api/predict/predictContractService'
import contractService from '@/api/contract/tPurchaseContractService'
import GridSelect from '@/components/gridSelect'
import purchaseService from '@/api/purchase/purchaseService'
import projectMainService from '@/api/project/projectMainService'
import { computed } from 'vue'
import dictUtils from '@/utils/dictUtils'
import FilePreview from '@/components/preview'
import OfficeSelect from '@/components/officeSelect'
export default {
  inject: {
    projectId: {
      from: 'projectId',
      default: computed(() => '')
    },
    purchaseId: {
      from: 'purchaseId',
      default: computed(() => '')
    }
  },
  data() {
    return {
      searchVisible: true,
      searchForm: {
        purchase: {
          id: ''
        },
        project: {
          id: ''
        },
        contractNo: '',
        contractName: '',
        contractFeature: '',
        contractType: '',
        contractSignTime: '',
        contractBeginTime: ''
      },
      purchaseService: purchaseService,
      projectMainService: projectMainService,
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [{ column: "a.create_time", asc: false }],
      },
      loading: false,
      syncDialogVisible: false, // 控制弹窗显示
      contractNo: '', // 合同编号输入值
      researchDialogVisible: false,
      activeTab: '1',
      researchForm: {
        contractName: '',
        contractNo: '',
        contractSignTime: '',
        contractAmount: '',
        correctContractAmount: '',
        taxRate: '',
        contractCategory: '',
        supplierName: '',
        topicName: '',
        correctTopicAmount: '',
        topicTaxRate: '',
        taxAmount: ''
      },
      researchRules: {
        contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        contractNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        contractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }]
      },
      contractDTO: {},
      title: '',
      dictUtils: dictUtils,
      contractCategory: "",
      downType:'',
      contractList:[]
    }
  },
  components: {
    GridSelect,
    ContractForm,
    FilePreview,
    OfficeSelect
  },
  watch: {
    purchaseId: {
      handler(newVal) {
        if (newVal) {
          console.log('purchaseId changed:', newVal)
          this.searchForm.purchase.id = newVal
          this.refreshList()
        }
      },
      immediate: true
    },
    projectId: {
      handler(newVal) {
        if (newVal) {
         
          this.searchForm.project.id = newVal

        }
      },
      immediate: true
    }
  },
  created() {
    this.refreshList()
  },
  mounted() {
    this.$nextTick(() => {
      // 将表格和工具栏进行关联
      const $table = this.$refs.contractTable
      const $toolbar = this.$refs.contractToolbar
      $table.connect($toolbar)
    })

    this.getListTips()
  },

  methods: {
    getListTips() {
      predictContractService.findByPurchaseId(this.searchForm.purchase.id).then(
        res => {
          this.title = '预计合同创建';
          res.forEach((item, index) => {
            this.title += this.dictUtils.getDictLabel("contract_type", item.contractCategory, '-') + '类型的合同，数量为' + item.planCount + (index == (res.length - 1) ? '。' : ",")
          })

        }
      )
    },
    // 获取数据列表
    refreshList() {
   

      this.loading = true
      contractService.list({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        ...this.searchForm
      }).then((data) => {
        this.dataList = data.records
        this.tablePage.total = data.total
        this.loading = false
      }).catch(error => {
        console.error('加载合同列表失败：', error)
        this.loading = false
      })
    },
    // 当前页
    currentChangeHandle({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
    // 排序
    sortChangeHandle(obj) {
      this.tablePage.orders = [];
      if (obj.order != null) {
        this.tablePage.orders = [{ column: obj.column.sortBy || this.$utils.toLine(obj.property), asc: obj.order === "asc" }];
      } else {
        this.tablePage.orders = [{ column: "a.create_time", asc: false }];
      }
      this.refreshList();
    },
    bindUnbindContract(id) {
      // id
      contractService.unbindContract({ contractNo: id }).then(res => {
        this.$message.success('解绑成功')
        this.refreshList();
      })
    },
    // 新增
    add(id) {

      this.$refs.contractForm.init('add', { projectId: this.projectId, purchaseId: this.purchaseId, id: id })
    },
    // 修改
    edit(id) {
      id = id || this.$refs.contractTable.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.contractForm.init('edit', id)
    },
    // 查看
    view(id) {
      // this.$refs.contractForm.init('view', id)

      
      this.$router.push({
        path: "/purchaseDetails/purchaseDetails",
        query: {
          purchaseId: this.purchaseId.value,
          projectId: this.projectId.value,
          id: id
        }
      })
    },
    // 删除
    del(id) {
      let ids = id || this.$refs.contractTable.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        predictContractService.delete(ids).then((data) => {
          this.$message.success(data)
          this.refreshList()
          this.loading = false
        })
      })
    },
    // 下载模板
    downloadTpl() {
      this.loading = true
      contractService
        .exportTemplate()
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, "合同管理导入模板");
          this.loading = false
        })
        .catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    // 自定义服务端导入
    importMethod({ file }) {
      // 处理表单
      const formBody = new FormData();
      formBody.append("file", file);
      this.loading = true
      contractService.importExcel(formBody).then((result) => {
        this.$message.success({
          dangerouslyUseHTMLString: true,
          message: result,
        });
        this.refreshList();
      });
    },
    // 自定义服务端导出
    exportMethod({ options }) {
      // 传给服务端的参数
      const params = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        orders: this.tablePage.orders,
        ...this.searchForm,
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        selectIds:
          options.mode === "selected"
            ? options.data.map((item) => item.id)
            : [],
        exportFields: options.columns.map(
          (column) => column.property && column.property.split(".")[0]
        ),
      };
      this.loading = true;
      return contractService
        .exportExcel(params)
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, options.filename);
          this.loading = false;
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.refreshList()
    },
    // 点击同步合同按钮
    showSyncDialog() {

      contractService.queryListByContractNo({projectId:this.projectId.value}).then(res=>{
            this.contractList=res
        this.syncDialogVisible = true
              this.contractNo = ''
      })
  
      
    },
    // 确认同步
    confirmSync() {
      if (!this.contractNo) {
        this.$message.warning('请选择要同步的合同')
        return
      }
      try {
        this.loading = true;
        let data = {
          "contractNo": this.contractNo,
          "contractFeature": "2",
          "projectId": this.projectId.value,
          "purchaseId": this.purchaseId.value,
          "downType":this.downType,
          contractCategory: this.contractCategory
        }
        contractService.queryByContractNo(data).then((res) => {
          this.loading = false
          this.$message.success('保存成功');
          this.syncDialogVisible = false;
          this.refreshList()
        })
      } catch (error) {
        this.loading = false
        this.$message.error('提交失败，请重试');
      }



    },
    deepClone(obj) {
      let objClone = Array.isArray(obj) ? [] : {}
      if (obj && typeof obj === 'object') {
        for (var key in obj) {
          if (obj.hasOwnProperty(key)) {
            // 判断ojb子元素是否为对象，如果是，递归复制
            if (obj[key] && typeof obj[key] === 'object') {
              objClone[key] = this.deepClone(obj[key])
            } else {
              // 如果不是，简单复制
              objClone[key] = obj[key]
            }
          }
        }
      }
      return objClone
    },
    // 打开添加科研弹窗
    openResearchDialog(row) {
      this.researchDialogVisible = true
      // 填充合同相关信息
      this.researchForm = row;
      this.contractDTO = this.deepClone(row);
      // this.researchForm.contractName = row.contractName
      // this.researchForm.contractNo = row.contractNo
      // this.researchForm.contractAmount = row.contractAmount
      // this.researchForm.correctContractAmount = row.correctContractAmount
      // this.researchForm.contractCategory = row.contractCategory
      // this.researchForm.supplierName = row.supplierName
    },
    // 提交科研表单
    submitResearchForm() {
      this.$refs.researchFormRef.validate((valid) => {
        if (valid) {
          // TODO: 调用保存科研信息的接口

          let data = {}
          if (this.activeTab == 1) {

            data = { contractId: this.researchForm.id, isAll: this.activeTab == 1 ? 1 : 2, TenantDTO: this.researchForm }
          } else {
            this.researchForm.supplier.tenantDTO={}
            let obj = {
              contractName: this.researchForm.topicName ? this.researchForm.topicName : this.researchForm.contractName,
              correctContractAmount: this.researchForm.correctTopicAmount ? this.researchForm.correctTopicAmount : this.researchForm.correctContractAmount, taxRate: this.researchForm.topicTaxRate ? this.researchForm.topicTaxRate : this.researchForm.taxRate,
              taxAmount: this.researchForm.taxAmount, project: this.researchForm.project, purchase: this.researchForm.purchase, contractNo: this.researchForm.contractNo, supplier: this.researchForm.supplier
            }

            data = { contractId: this.researchForm.id, isAll: this.activeTab == 1 ? 1 : 2, scienceContractDTO: obj, }
          }

          contractService.splitContract(data).then((data) => {
            this.$message.success('提交成功');
            this.researchDialogVisible = false
            this.refreshList()
          })


        }
      })
    },
    previewFiles(url) {
      this.$refs.filePreview.open(url)
    },
    getFileName(attachment) {
      if (!attachment) return '';
      if (attachment.indexOf('&fileName=') != -1) {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&fileName=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      } else {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&name=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      }

    },
  }
}
</script>

<style scoped lang="scss">
.sync-dialog-content {
  padding: 10px 20px;
  display: flex;
  align-items: center;
  .input-label {
    font-size: 14px;
    color: #606266;
    margin-right: 10px;
  }

  .contract-input {
    width: 80%;
  }
}

.dialog-footer {
  text-align: center;
  padding-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #409eff;
  background-color: #f5f7fa;
  line-height: 40px;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>

